/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.model.component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;

/**
 * Used to parse applet code.
 *
 * As the applet code
 * might change in the future, this class encapsulates the
 * changes, as far as parsing is concerned.
 * 
 * @author Walter Lütgenau
 */
public class ComponentDialogParser {
    String parameterString;
    
    public static final String PARAMETER_SEPARATOR = ";";

    /**
     * Initialize the applet parser with the HTML string.
     * 
     * @param html
     */
    public ComponentDialogParser(String parameterString) {
        this.parameterString = parameterString;
    }

    /**
     * Return the information about the applet
     * in a data object.
     * 
     * @return the info
     * @throws IOException
     */
    public AppletInfo getAppletInfo() throws IOException {
        HashMap<String, String> parameters = getParameters();
        String name = parameters.get(ComponentEditorParser.PAR_CODE);
        if (name == null)
            return null;

        parameters.remove(ComponentEditorParser.PAR_CODE);

        return new AppletInfo(name, parameters);
    }

    /**
     * Parse the applet parameters into a map.
     *
     * Build a hashmap of the applet parameters and return it.
     *
     * @return the applet parameters
     * @throws IOException
     */
    protected HashMap<String, String> getParameters() throws IOException {
        HashMap<String, String> parameterMap = new HashMap<String, String>();

        String[] parameters = parameterString.split(PARAMETER_SEPARATOR);
        for (int i = 0; i < parameters.length; i++) {
            String key = parameters[i];
            String value = parameters[++i];
            
            parameterMap.put(key, value);
        }
        
        return parameterMap;
    }
}
